<template>
  <div class="parking-map">
    <div id="map-container" class="map-container">
      <div v-if="loading" class="map-loading">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <span>地图加载中...</span>
      </div>
      <div v-if="error" class="map-error">
        <el-icon><Warning /></el-icon>
        <span>{{ error }}</span>
        <el-button type="primary" size="small" @click="reloadMap">重试</el-button>
      </div>
    </div>
    <div class="map-controls">
      <el-button-group>
        <el-button @click="locateUser" :loading="locating">
          <el-icon><Location /></el-icon>
          定位
        </el-button>
        <el-button @click="toggleTraffic" :loading="loadingTraffic">
          <el-icon><Van /></el-icon>
          {{ showTraffic ? '关闭路况' : '显示路况' }}
        </el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Location, Van, Loading, Warning } from '@element-plus/icons-vue'

export default {
  name: 'ParkingMap',
  components: {
    Location,
    Van,
    Loading,
    Warning
  },
  props: {
    parkingLots: {
      type: Array,
      default: () => []
    },
    center: {
      type: Object,
      default: () => ({ lng: 120.149506, lat: 30.242853 })
    },
    zoom: {
      type: Number,
      default: 14
    }
  },
  emits: ['select-parking'],
  setup(props, { emit }) {
    const map = ref(null)
    const markers = ref([])
    const showTraffic = ref(false)
    const userLocation = ref(null)
    const loading = ref(true)
    const error = ref('')
    const locating = ref(false)
    const loadingTraffic = ref(false)
    const mapScript = ref(null)

    // 初始化地图
    const initMap = () => {
      try {
        map.value = new AMap.Map('map-container', {
          zoom: props.zoom,
          center: [props.center.lng, props.center.lat],
          viewMode: '3D',
          resizeEnable: true,
          zoomEnable: true,
          dragEnable: true,
          jogEnable: true,
          animateEnable: true,
          keyboardEnable: true,
          doubleClickZoom: true,
          scrollWheel: true,
          touchZoom: true,
          showIndoorMap: true,
          showBuildingBlock: true
        })

        // 添加地图控件
        map.value.addControl(new AMap.Scale())
        map.value.addControl(new AMap.ToolBar())
        map.value.addControl(new AMap.MapType())

        // 监听地图加载完成事件
        map.value.on('complete', () => {
          loading.value = false
          addMarkers()
        })

        // 监听地图错误事件
        map.value.on('error', (e) => {
          error.value = '地图加载失败，请重试'
          loading.value = false
        })
      } catch (e) {
        error.value = '地图初始化失败，请重试'
        loading.value = false
      }
    }

    // 添加停车场标记
    const addMarkers = () => {
      if (!map.value) return

      // 清除现有标记
      markers.value.forEach(marker => marker.setMap(null))
      markers.value = []

      props.parkingLots.forEach(lot => {
        const marker = new AMap.Marker({
          position: [lot.longitude, lot.latitude],
          title: lot.name,
          icon: new AMap.Icon({
            size: new AMap.Size(32, 32),
            image: lot.availableSpaces > 0 ? '/markers/parking-available.png' : '/markers/parking-full.png',
            imageSize: new AMap.Size(32, 32)
          }),
          offset: new AMap.Pixel(-16, -16),
          animation: 'AMAP_ANIMATION_DROP'
        })

        // 添加信息窗体
        const infoWindow = new AMap.InfoWindow({
          content: `
            <div class="parking-info">
              <h4>${lot.name}</h4>
              <p>总车位：${lot.totalSpaces}</p>
              <p>可用车位：${lot.availableSpaces}</p>
              <p>收费标准：${lot.hourlyRate}元/小时</p>
              <button onclick="selectParking(${lot.id})">选择此停车场</button>
            </div>
          `,
          offset: new AMap.Pixel(0, -30),
          closeWhenClickMap: true
        })

        // 点击标记显示信息窗体
        marker.on('click', () => {
          infoWindow.open(map.value, marker.getPosition())
        })

        marker.setMap(map.value)
        markers.value.push(marker)
      })

      // 自适应地图视野
      if (markers.value.length > 0) {
        map.value.setFitView()
      }
    }

    // 定位用户位置
    const locateUser = async () => {
      if (!map.value) return
      
      locating.value = true
      try {
        AMap.plugin('AMap.Geolocation', () => {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            buttonPosition: 'RB',
            buttonOffset: new AMap.Pixel(10, 20),
            zoomToAccuracy: true
          })

          map.value.addControl(geolocation)
          geolocation.getCurrentPosition((status, result) => {
            locating.value = false
            if (status === 'complete') {
              userLocation.value = {
                lng: result.position.lng,
                lat: result.position.lat
              }
              map.value.setCenter([result.position.lng, result.position.lat])
              ElMessage.success('定位成功')
            } else {
              ElMessage.error('定位失败')
            }
          })
        })
      } catch (e) {
        locating.value = false
        ElMessage.error('定位服务不可用')
      }
    }

    // 切换路况显示
    const toggleTraffic = () => {
      if (!map.value) return
      
      loadingTraffic.value = true
      try {
        showTraffic.value = !showTraffic.value
        if (showTraffic.value) {
          map.value.addControl(new AMap.TileLayer.Traffic())
        } else {
          map.value.removeControl(map.value.getAllOverlays('traffic')[0])
        }
      } catch (e) {
        ElMessage.error('切换路况显示失败')
      } finally {
        loadingTraffic.value = false
      }
    }

    // 重新加载地图
    const reloadMap = () => {
      error.value = ''
      loading.value = true
      if (mapScript.value) {
        document.head.removeChild(mapScript.value)
      }
      loadMapScript()
    }

    // 加载地图脚本
    const loadMapScript = () => {
      mapScript.value = document.createElement('script')
      mapScript.value.src = `https://webapi.amap.com/maps?v=2.0&key=${import.meta.env.VITE_AMAP_KEY}&plugin=AMap.Scale,AMap.ToolBar,AMap.MapType,AMap.Geolocation,AMap.TileLayer.Traffic`
      mapScript.value.async = true
      mapScript.value.onload = () => {
        initMap()
      }
      mapScript.value.onerror = () => {
        error.value = '地图脚本加载失败，请检查网络连接'
        loading.value = false
      }
      document.head.appendChild(mapScript.value)
    }

    // 选择停车场
    const selectParking = (id) => {
      emit('select-parking', id)
    }

    onMounted(() => {
      loadMapScript()
    })

    onUnmounted(() => {
      if (map.value) {
        map.value.destroy()
      }
      if (mapScript.value) {
        document.head.removeChild(mapScript.value)
      }
    })

    return {
      loading,
      error,
      locating,
      loadingTraffic,
      showTraffic,
      locateUser,
      toggleTraffic,
      reloadMap
    }
  }
}
</script>

<style scoped>
.parking-map {
  position: relative;
  width: 100%;
  height: 100%;
}

.map-container {
  width: 100%;
  height: 100%;
  min-height: 500px;
  position: relative;
}

.map-loading,
.map-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  background: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.loading-icon {
  font-size: 24px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.map-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 100;
}

:deep(.parking-info) {
  padding: 10px;
}

:deep(.parking-info h4) {
  margin: 0 0 10px 0;
  font-size: 16px;
}

:deep(.parking-info p) {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
}

:deep(.parking-info button) {
  width: 100%;
  padding: 8px;
  margin-top: 10px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

:deep(.parking-info button:hover) {
  background-color: #66b1ff;
}
</style> 